<template>
  <div style="margin:16px auto; max-width: 1080px; padding: 0 12px;">
    <a-card title="角色管理">
      <template #extra>
        <a-space>
          <a-input v-model:value="keyword" placeholder="按编码/名称筛选" style="width: 240px" />
          <a-button type="primary" @click="load">查询</a-button>
          <a-button v-if="hasPerm('role:manage')" type="primary" @click="openEdit()">新建</a-button>
        </a-space>
      </template>
      <a-table :data-source="roles" :columns="columns" row-key="id" :pagination="false">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key==='actions'">
            <a v-if="hasPerm('role:manage')" @click="openPerm(record)">分配权限</a>
            <a-divider type="vertical" v-if="hasPerm('role:manage')" />
            <a v-if="hasPerm('role:manage')" @click="openEdit(record)">编辑</a>
            <a-divider type="vertical" v-if="hasPerm('role:manage')" />
            <a-popconfirm v-if="hasPerm('role:manage')" title="确认删除该角色？" @confirm="() => onDelete(record.id)"><a>删除</a></a-popconfirm>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal v-model:open="editOpen" :title="editForm.id ? '编辑角色' : '新建角色'" @ok="onSave" ok-text="保存" cancel-text="取消">
      <a-form :model="editForm" label-col="{span:5}" wrapper-col="{span:19}">
        <a-form-item label="编码"><a-input v-model:value="editForm.code" :disabled="!!editForm.id" /></a-form-item>
        <a-form-item label="名称"><a-input v-model:value="editForm.name" /></a-form-item>
        <a-form-item label="描述"><a-input v-model:value="editForm.description" /></a-form-item>
        <a-form-item label="数据范围">
          <a-select v-model:value="editForm.dataScope" :options="[
            {label:'SELF', value:'SELF'},
            {label:'ALL', value:'ALL'}
          ]" />
        </a-form-item>
        <a-form-item label="状态">
          <a-switch v-model:checked="statusOn" />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal v-model:open="permOpen" title="分配权限" @ok="savePerms" ok-text="保存" cancel-text="取消" width="900px">
      <a-space style="margin-bottom: 12px">
        <a-input v-model:value="pkeyword" placeholder="按编码/名称/路径筛选" style="width: 260px" />
        <a-button type="primary" @click="loadPerms">查询</a-button>
      </a-space>
      <div style="display:flex; gap:16px">
        <div style="flex:1">
          <a-list :data-source="permissions" bordered>
            <template #renderItem="{ item }">
              <a-list-item>
                <a-checkbox v-model:checked="checkedPermMap[(item as any).id]">
                  {{ (item as any).code }}
                  <span class="muted" v-if="(item as any).path"> - {{ (item as any).path }}</span>
                </a-checkbox>
              </a-list-item>
            </template>
          </a-list>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { message } from 'ant-design-vue'
import { listRoles, listPermissions, createRole, updateRole, deleteRole, getRolePermIds, setRolePermIds, type RoleVO, type PermissionVO } from '@/api/admin/modules/system'
import { usePerm } from '@/composables/usePerm'

const keyword = ref('')
const roles = ref<RoleVO[]>([])
const columns = computed(() => [
  { title: 'ID', dataIndex: 'id' },
  { title: '编码', dataIndex: 'code' },
  { title: '名称', dataIndex: 'name' },
  { title: '数据范围', dataIndex: 'dataScope' },
  { title: '状态', dataIndex: 'status', customRender: ({ text }: any) => (text === 1 ? '启用' : '禁用') },
  { title: '创建时间', dataIndex: 'createTime' },
  { title: '操作', key: 'actions' }
])

async function load() {
  const resp = await listRoles(keyword.value || undefined)
  if (resp.code === 0) roles.value = resp.data
}

const editOpen = ref(false)
const editForm = ref<{ id?: number; code: string; name: string; description?: string; dataScope?: string; status?: number }>({ code: '', name: '', description: '', dataScope: 'SELF', status: 1 })
const statusOn = computed({ get: () => editForm.value.status === 1, set: (v: boolean) => editForm.value.status = v ? 1 : 0 })
const { hasPerm } = usePerm()

function openEdit(row?: any) {
  if (row) editForm.value = { id: row.id, code: row.code, name: row.name, description: row.description, dataScope: row.dataScope, status: row.status }
  else editForm.value = { code: '', name: '', description: '', dataScope: 'SELF', status: 1 }
  editOpen.value = true
}

async function onSave() {
  if (!editForm.value.name || !editForm.value.code) { message.warning('请填写编码与名称'); return }
  if (editForm.value.id) {
    const resp = await updateRole(editForm.value.id, { name: editForm.value.name, description: editForm.value.description, dataScope: editForm.value.dataScope, status: editForm.value.status })
    if (resp.code === 0) { message.success('已保存'); editOpen.value = false; load() }
  } else {
    const resp = await createRole(editForm.value)
    if (resp.code === 0) { message.success('已创建'); editOpen.value = false; load() }
  }
}

async function onDelete(id: number) {
  const resp = await deleteRole(id)
  if (resp.code === 0) { message.success('已删除'); load() }
}

// 分配权限
const permOpen = ref(false)
const currentRoleId = ref<number | null>(null)
const permissions = ref<PermissionVO[]>([])
const checkedPermMap = ref<Record<number, boolean>>({})
const pkeyword = ref('')

function openPerm(row: any) {
  currentRoleId.value = row.id
  permOpen.value = true
  loadPerms()
}

async function loadPerms() {
  const [lp, assigned] = await Promise.all([
    listPermissions(pkeyword.value || undefined),
    currentRoleId.value ? getRolePermIds(currentRoleId.value) : Promise.resolve({ code: -1, data: [] } as any)
  ])
  if (lp.code === 0) permissions.value = lp.data
  checkedPermMap.value = {}
  if (assigned.code === 0) for (const id of assigned.data) checkedPermMap.value[id as number] = true
}

async function savePerms() {
  if (!currentRoleId.value) return
  const ids = Object.keys(checkedPermMap.value).filter(k => checkedPermMap.value[Number(k)]).map(k => Number(k))
  const resp = await setRolePermIds(currentRoleId.value, ids)
  if (resp.code === 0) { message.success('已保存'); permOpen.value = false }
}

load()
</script>


